package tech.heptagram.staff.api.v3;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

import javax.annotation.Resource;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import tech.heptagram.core.common.rest.ResponseResult;

/**
 * @author wang.yuchuan
 * @createdAt 2019/4/28
 */
@Api("redis缓存管理相关api")
@RestController
@RequestMapping("/api/v3/cache/redis")
@Slf4j
public class RedisApiRestController {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @ApiOperation("获取所有key")
    @GetMapping("keys")
    public ResponseResult<Set> keys() {

        Set<Object> keys = redisTemplate.keys("*");

        return new ResponseResult<>(keys);
    }

    @ApiOperation("获取指定key的值")
    @GetMapping("get/{key}")
    public ResponseResult getValue(@PathVariable("key") String key) {
        Object value = redisTemplate.opsForValue().get(key);
        return new ResponseResult(value);
    }

    @ApiOperation("清除指定key的缓存")
    @GetMapping("del/{key}")
    public ResponseResult remove(@PathVariable("key") String key) {
        Boolean result = redisTemplate.delete(key);
        return new ResponseResult(result);
    }

    @ApiOperation("清除以指定字符串开头的所有key的缓存, 如: staff:*")
    @GetMapping("delall/{prefix}")
    public ResponseResult removeAll(@PathVariable("prefix") String keyPrefix) {

        Set<Object> keys = redisTemplate.keys(keyPrefix);
        Long deleteCount = redisTemplate.delete(keys);
        return new ResponseResult(deleteCount);
    }

    @GetMapping("cas/keys")
    public ResponseResult casRedisKeys() {
        Jedis jedis = new Jedis("cas-redis.pro-bootstrap-intranet", 6379);
        jedis.select(3);
        Set<String> keys = jedis.keys("*");
        return new ResponseResult(keys);
    }
}
